﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace UFIDA.U8.YYNBJY.PUBMethod
{
    public delegate void delInfoList(string text); //定义委托
    public class PMethod
    {
        FRMain frm = new FRMain();
        public RichTextBox richtxt;
        public static TextBox textid;

        #region 前台日志
        /// <summary>
        /// 前台写入日志
        /// </summary>
        /// <param name="error"></param>
        /// <returns></returns>
        public static string printmsg(string error)
        {
            FRMain.form1.richtxt.SelectionStart = FRMain.form1.richtxt.TextLength;
            FRMain.form1.richtxt.ScrollToCaret();
            FRMain.form1.richtxt.SelectedText = error + "\n";
            return error;
        }
        /// <summary>
        /// 前台日志输出+写入log
        /// </summary>
        /// <param name="filename">log文件名</param>
        /// <param name="error">日志内容</param>
        /// <param name="mlog">前台是否日志</param>
        /// <param name="ilog">TXT日志开关</param>
        /// <param name="iilog">TXT日志开关</param>
        /// <param name="color">前台日志颜色</param>
        /// <returns></returns>
        public static string printmsgs(string filename,string error,bool mlog, bool ilog,bool iilog,System.Drawing.Color color)
        {
            if (ilog||iilog)
            {
                DBHelp.LogException.WriteiLog(filename,error,ilog,iilog);
            }
            if (FRMain.form1.richtxt.Lines.Length > 50000)
            {
                FRMain.form1.richtxt.Clear();
            }
            if (mlog)
            {
                FRMain.form1.richtxt.SelectionStart = FRMain.form1.richtxt.TextLength;
                FRMain.form1.richtxt.ScrollToCaret();
                FRMain.form1.richtxt.SelectionColor = color;
                FRMain.form1.richtxt.SelectedText = error + "\n";
            }
            return error;
        }
        #endregion

        /// <summary>
        /// 截取指定字节长度的字符串
        /// </summary>
        /// <param name="str">原字符串</param>
        /// <param name="len">截取字节长度</param>
        /// <returns></returns>
        public static string CutByteString(string str, int len)
        {
            string result = string.Empty;// 最终返回的结果
            if (string.IsNullOrEmpty(str)) { return result; }
            int byteLen = System.Text.Encoding.Default.GetByteCount(str);// 单字节字符长度
            int charLen = str.Length;// 把字符平等对待时的字符串长度
            int byteCount = 0;// 记录读取进度
            int pos = 0;// 记录截取位置
            if (byteLen > len)
            {
                for (int i = 0; i < charLen; i++)
                {
                    if (Convert.ToInt32(str.ToCharArray()[i]) > 255)// 按中文字符计算加2
                    { byteCount += 3; }
                    else// 按英文字符计算加1
                    { byteCount += 1; }
                    if (byteCount > len)// 超出时只记下上一个有效位置
                    {
                        pos = i;
                        break;
                    }
                    else if (byteCount == len)// 记下当前位置
                    {
                        pos = i + 1;
                        break;
                    }
                }
                if (pos >= 0)
                { result = str.Substring(0, pos); }
            }
            else
            { result = str; }
            return result;
        }




        /// <summary>
        /// 截取指定字节长度的字符串
        /// </summary>
        /// <param name="str">原字符串</param>
        /// <param name="startIndex">起始位置</param>
        /// <param name="len">截取字节长度</param>
        /// <returns></returns>
        public static string CutByteString(string str, int startIndex, int len)
        {
            string result = string.Empty;// 最终返回的结果
            if (string.IsNullOrEmpty(str)) { return result; }

            int byteLen = System.Text.Encoding.Default.GetByteCount(str);// 单字节字符长度
            int charLen = str.Length;// 把字符平等对待时的字符串长度

            if (startIndex == 0)
            { return CutByteString(str, len); }
            else if (startIndex >= byteLen)
            { return result; }
            else //startIndex < byteLen
            {
                int AllLen = startIndex + len;
                int byteCountStart = 0;// 记录读取进度
                int byteCountEnd = 0;// 记录读取进度
                int startpos = 0;// 记录截取位置                
                int endpos = 0;// 记录截取位置
                for (int i = 0; i < charLen; i++)
                {
                    if (Convert.ToInt32(str.ToCharArray()[i]) > 255)// 按中文字符计算加2
                    { byteCountStart += 2; }
                    else// 按英文字符计算加1
                    { byteCountStart += 1; }
                    if (byteCountStart > startIndex)// 超出时只记下上一个有效位置
                    {
                        startpos = i;
                        AllLen = startIndex + len - 1;
                        break;
                    }
                    else if (byteCountStart == startIndex)// 记下当前位置
                    {
                        startpos = i + 1;
                        break;
                    }
                }

                if (startIndex + len <= byteLen)//截取字符在总长以内
                {
                    for (int i = 0; i < charLen; i++)
                    {
                        if (Convert.ToInt32(str.ToCharArray()[i]) > 255)// 按中文字符计算加2
                        { byteCountEnd += 2; }
                        else// 按英文字符计算加1
                        { byteCountEnd += 1; }
                        if (byteCountEnd > AllLen)// 超出时只记下上一个有效位置
                        {
                            endpos = i;
                            break;
                        }
                        else if (byteCountEnd == AllLen)// 记下当前位置
                        {
                            endpos = i + 1;
                            break;
                        }
                    }
                    endpos = endpos - startpos;
                }
                else if (startIndex + len > byteLen)//截取字符超出总长
                {
                    endpos = charLen - startpos;
                }
                if (endpos >= 0)
                { result = str.Substring(startpos, endpos); }
            }
            return result;
        }

        /// <summary>
        /// 创建一个按时间排序的Guid
        /// </summary>
        /// <returns></returns>
        public static string GetID()
        {
            byte[] guidArray = Guid.NewGuid().ToByteArray();
            DateTime now = DateTime.Now;

            DateTime baseDate = new DateTime(1900, 1, 1);

            TimeSpan days = new TimeSpan(now.Ticks - baseDate.Ticks);

            TimeSpan msecs = new TimeSpan(now.Ticks - (new DateTime(now.Year, now.Month, now.Day).Ticks));
            byte[] daysArray = BitConverter.GetBytes(days.Days);
            byte[] msecsArray = BitConverter.GetBytes((long)(msecs.TotalMilliseconds / 3.333333));

            Array.Copy(daysArray, 0, guidArray, 2, 2);
            //毫秒高位
            Array.Copy(msecsArray, 2, guidArray, 0, 2);
            //毫秒低位
            Array.Copy(msecsArray, 0, guidArray, 4, 2);
            return new System.Guid(guidArray).ToString();
        }

        ///   <summary> 
        ///   将指定字符串按指定长度进行截取并加上指定的后缀
        ///   </summary> 
        ///   <param   name= "oldStr "> 需要截断的字符串 </param> 
        ///   <param   name= "maxLength "> 字符串的最大长度 </param> 
        ///   <param   name= "endWith "> 超过长度的后缀 </param> 
        ///   <returns> 如果超过长度，返回截断后的新字符串加上后缀，否则，返回原字符串 </returns> 
        public static string StringTruncat(string oldStr, int maxLength, string endWith)
        {
            //判断原字符串是否为空
            if (string.IsNullOrEmpty(oldStr))
                return oldStr + endWith;

            //返回字符串的长度必须大于1
            if (maxLength < 1)
                throw new Exception("返回的字符串长度必须大于[0] ");

            //判断原字符串是否大于最大长度
            if (oldStr.Length > maxLength)
            {
                //截取原字符串
                string strTmp = oldStr.Substring(0, maxLength);

                //判断后缀是否为空
                if (string.IsNullOrEmpty(endWith))
                    return strTmp;
                else
                    return strTmp + endWith;
            }
            return oldStr;
        }


        ///<summary>
        ///数据空时处理
        ///</summary>
        ///<param zdlx>字段类型</param>
        ///<param zd>字段值</param>
        ///<returns>处理后字段值</returns>
        public static string setvalue(int zdlx, string zd)
        {
            string newzd = zd;
            if (zdlx == 1) //数值
            {
                if (string.IsNullOrEmpty(zd))
                    newzd = "0";
            }
            if (zdlx == 2) //字符
            {
                if (string.IsNullOrEmpty(zd))
                    newzd = "NULL";
                else
                    newzd = "'" + zd + "'";
            }
            return newzd;
        }


        public static long GetUnixTime(DateTime time)
        {
            return (time.ToUniversalTime().Ticks / 10000000 - 62135596800);
        }
        //时间转到时间戳   秒
        private int GetTimeStamp(DateTime dt)
        {
            DateTime dateStart = new DateTime(1970, 1, 1, 8, 0, 0);
            int timeStamp = Convert.ToInt32((dt - dateStart).TotalSeconds);
            return timeStamp;
        }

        public static long DateTimeToTimestamp(DateTime datetime)
        {
            DateTime dd = new DateTime(1970, 1, 1, 0, 0, 0, 0);
            DateTime timeUTC = DateTime.SpecifyKind(datetime, DateTimeKind.Utc);//本地时间转成UTC时间
            TimeSpan ts = (timeUTC - dd);
            return (Int64)ts.TotalMilliseconds;//精确到毫秒
        }

        private Int32 ConvertDateTimeToInt32(string dt)
        {
            DateTime dt1 = new DateTime(1970, 1, 1, 8, 0, 0);
            DateTime dt2 = Convert.ToDateTime(dt);
            return Convert.ToInt32((dt2 - dt1).TotalSeconds);
        }
        #region HTTPPOST请求方法
        /// <summary>
        /// POST请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="parameters"></param>
        /// <param name="cookies"></param>
        /// <returns></returns>
        public static string CreatePostHttpResponses(string url, string parameters, CookieCollection cookies)
        {
            try
            {
                HttpWebRequest request = null;
                //如果是发送HTTPS请求  
                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    request = WebRequest.Create(url) as HttpWebRequest;
                }
                else
                {
                    request = WebRequest.Create(url) as HttpWebRequest;
                }
                request.Method = "POST";
                //request.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
                request.ContentType = "application/json;charset=utf-8";
                if (cookies != null)
                {
                    request.CookieContainer = new CookieContainer();
                    request.CookieContainer.Add(cookies);
                }
                byte[] data = Encoding.UTF8.GetBytes(parameters.ToString());
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
                string[] values = request.Headers.GetValues("Content-Type");
                Stream myResponseStream = request.GetResponse().GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                string retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();
                return retString;
            }
            catch (Exception ex)
            {
                return "false" + ex.Message;
            }
        }
        /// <summary>
        /// 每刻POST请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="parameters"></param>
        /// <param name="cookies"></param>
        /// <returns></returns>
        public static string MKCreatePostHttpResponses(string url,string entCode, string tokenId, string parameters, CookieCollection cookies)
        {
            try
            {
                HttpWebRequest request = null;
                //如果是发送HTTPS请求  
                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    request = WebRequest.Create(url) as HttpWebRequest;
                }
                else
                {
                    request = WebRequest.Create(url) as HttpWebRequest;
                }
                request.Method = "POST";
                request.ContentType = "application/json;charset=utf-8";
                if (!string.IsNullOrEmpty(entCode))
                {
                    request.Headers.Add("entCode", entCode);
                }
                //Bearer + 空格 + token
                request.Headers.Add("Authorization", "Bearer "+tokenId.Trim());
                if (cookies != null)
                {
                    request.CookieContainer = new CookieContainer();
                    request.CookieContainer.Add(cookies);
                }
                byte[] data = Encoding.UTF8.GetBytes(parameters.ToString());
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
                string[] values = request.Headers.GetValues("Content-Type");
                Stream myResponseStream = request.GetResponse().GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                string retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();
                return retString;
            }
            catch (Exception ex)
            {
                return "false" + ex.Message;
            }
        }
        #endregion
        //POST方式的HTTP请求  
        public static string CreatePostHttpResponse(string url, string parameters, string[] head, CookieCollection cookies)
        {
            HttpWebRequest request = null;
            //如果是发送HTTPS请求  
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                request = WebRequest.Create(url) as HttpWebRequest;
            }
            else
            {
                request = WebRequest.Create(url) as HttpWebRequest;
            }
            request.Method = "POST";
            //request.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
            request.ContentType = "application/json;charset=utf-8";

            string ab = head[0];
            string bb = head[1];
            request.Headers.Add("entcode:" + ab);
            request.Headers.Add("tokenID:" + bb);
            //request.Headers.Add("entCode:" + head[0],"tokenid:" +head[1]) ;
            //request.Headers = ();//错误写法 

            if (cookies != null)
            {
                request.CookieContainer = new CookieContainer();
                request.CookieContainer.Add(cookies);
            }

            //byte[] data = Encoding.ASCII.GetBytes(parameters.ToString());
            byte[] data = Encoding.UTF8.GetBytes(parameters.ToString());

            using (Stream stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }

            string[] values = request.Headers.GetValues("Content-Type");
            Stream myResponseStream = request.GetResponse().GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            return retString;
        }
        /// <summary>
        /// 高精度延时,窗口程序不卡死延时
        /// </summary>
        /// <param name="time">1000微秒 = 1毫秒 ； 1000毫秒 = 1秒</param>
        /// <param name="type">可空:毫秒  0：毫秒  1：微秒  2：秒  3：分  4：小时  5：天</param>
        public static void SuperSleep(int time, int type = 2)
        {
            if (time < 1)
            {
                return;
            }

            int hTimer = 0;
            long Interval = 0;
            int i = 0;

            int INFINITE = -1;
            int QS_ALLINPUT = 255;
            int WAIT_OBJECT_0 = 0;

            if (type == 1)
            {
                Interval = -10 * time;
                hTimer = CreateWaitableTimer(0, true, "WaitableTimer");
                SetWaitableTimer(hTimer, ref Interval, 0, 0, 0, false);

                while (MsgWaitForMultipleObjects(1, ref hTimer, false, INFINITE, QS_ALLINPUT) != WAIT_OBJECT_0)
                {
                    System.Windows.Forms.Application.DoEvents();
                }

                CloseHandle(hTimer);
                return;
            }
            if (type == 0)
            {
                type = 1;
            }
            if (type == 2)
            {
                type = 1000;
            }
            if (type == 3)
            {
                type = 1000 * 60;
            }
            if (type == 4)
            {
                type = 1000 * 60 * 60;
            }
            if (type == 5)
            {
                type = 1000 * 60 * 60 * 24;
            }

            Interval = -10 * time * 1000 * type;
            hTimer = CreateWaitableTimer(0, true, "WaitableTimer");
            SetWaitableTimer(hTimer, ref Interval, 0, 0, 0, false);
            while (MsgWaitForMultipleObjects(1, ref hTimer, false, INFINITE, QS_ALLINPUT) != WAIT_OBJECT_0)
            {
                System.Windows.Forms.Application.DoEvents();
            }
            CloseHandle(hTimer);
        }
        /// <summary>
        /// 创建或打开一个可等待的计时器对象
        /// </summary>
        /// <param name="lpTimerAttributes"></param>
        /// <param name="bManualReset"></param>
        /// <param name="lpTimerName"></param>
        /// <returns></returns>
        [DllImport("kernel32.dll")]
        private static extern int CreateWaitableTimer(int lpTimerAttributes, bool bManualReset, string lpTimerName);

        /// <summary>
        /// 激活指定的等待计时器
        /// </summary>
        /// <param name="hTimer"></param>
        /// <param name="ft"></param>
        /// <param name="lPeriod"></param>
        /// <param name="pfnCompletionRoutine"></param>
        /// <param name="pArgToCompletionRoutine"></param>
        /// <param name="fResume"></param>
        /// <returns></returns>
        [DllImport("kernel32.dll")]
        static extern bool SetWaitableTimer(int hTimer, [In] ref long pDueTime, int lPeriod, int pfnCompletionRoutine, int pArgToCompletionRoutine, bool fResume);

        /// <summary>
        /// 等待直到一个或所有指定对象处于信号状态或超时间隔过去
        /// </summary>
        /// <param name="nCount"></param>
        /// <param name="pHandles"></param>
        /// <param name="fWaitAll"></param>
        /// <param name="dwMilliseconds"></param>
        /// <param name="dwWakeMask"></param>
        /// <returns></returns>
        [DllImport("user32.dll")]
        private static extern int MsgWaitForMultipleObjects(int nCount, ref int pHandles, bool fWaitAll, int dwMilliseconds, int dwWakeMask);

        /// <summary>
        /// 关闭打开的对象句柄。
        /// </summary>
        /// <param name="hObject"></param>
        /// <returns></returns>
        [DllImport("kernel32.dll")]
        private static extern int CloseHandle(int hObject);

        #region 金额大小写转换
        /// <summary>
        /// 金额转换成中文大写金额
        /// </summary>
        /// <param name="LowerMoney">eg:10.74</param>
        /// <returns></returns>
        public static string MoneyToUpper(string LowerMoney)
        {
            string functionReturnValue = null;
            bool IsNegative = false; // 是否是负数
            if (LowerMoney.Trim().Substring(0, 1) == "-")
            {
                // 是负数则先转为正数
                LowerMoney = LowerMoney.Trim().Remove(0, 1);
                IsNegative = true;
            }
            string strLower = null;
            string strUpart = null;
            string strUpper = null;
            int iTemp = 0;
            // 保留两位小数 123.489→123.49　　123.4→123.4
            LowerMoney = Math.Round(double.Parse(LowerMoney), 2).ToString();
            if (LowerMoney.IndexOf(".") > 0)
            {
                if (LowerMoney.IndexOf(".") == LowerMoney.Length - 2)
                {
                    LowerMoney = LowerMoney + "0";
                }
            }
            else
            {
                LowerMoney = LowerMoney + ".00";
            }
            strLower = LowerMoney;
            iTemp = 1;
            strUpper = "";
            while (iTemp <= strLower.Length)
            {
                switch (strLower.Substring(strLower.Length - iTemp, 1))
                {
                    case ".":
                        strUpart = "圆";
                        break;
                    case "0":
                        strUpart = "零";
                        break;
                    case "1":
                        strUpart = "壹";
                        break;
                    case "2":
                        strUpart = "贰";
                        break;
                    case "3":
                        strUpart = "叁";
                        break;
                    case "4":
                        strUpart = "肆";
                        break;
                    case "5":
                        strUpart = "伍";
                        break;
                    case "6":
                        strUpart = "陆";
                        break;
                    case "7":
                        strUpart = "柒";
                        break;
                    case "8":
                        strUpart = "捌";
                        break;
                    case "9":
                        strUpart = "玖";
                        break;
                }

                switch (iTemp)
                {
                    case 1:
                        strUpart = strUpart + "分";
                        break;
                    case 2:
                        strUpart = strUpart + "角";
                        break;
                    case 3:
                        strUpart = strUpart + "";
                        break;
                    case 4:
                        strUpart = strUpart + "";
                        break;
                    case 5:
                        strUpart = strUpart + "拾";
                        break;
                    case 6:
                        strUpart = strUpart + "佰";
                        break;
                    case 7:
                        strUpart = strUpart + "仟";
                        break;
                    case 8:
                        strUpart = strUpart + "万";
                        break;
                    case 9:
                        strUpart = strUpart + "拾";
                        break;
                    case 10:
                        strUpart = strUpart + "佰";
                        break;
                    case 11:
                        strUpart = strUpart + "仟";
                        break;
                    case 12:
                        strUpart = strUpart + "亿";
                        break;
                    case 13:
                        strUpart = strUpart + "拾";
                        break;
                    case 14:
                        strUpart = strUpart + "佰";
                        break;
                    case 15:
                        strUpart = strUpart + "仟";
                        break;
                    case 16:
                        strUpart = strUpart + "万";
                        break;
                    default:
                        strUpart = strUpart + "";
                        break;
                }

                strUpper = strUpart + strUpper;
                iTemp = iTemp + 1;
            }

            strUpper = strUpper.Replace("零拾", "零");
            strUpper = strUpper.Replace("零佰", "零");
            strUpper = strUpper.Replace("零仟", "零");
            strUpper = strUpper.Replace("零零零", "零");
            strUpper = strUpper.Replace("零零", "零");
            strUpper = strUpper.Replace("零角零分", "整");
            strUpper = strUpper.Replace("零分", "整");
            strUpper = strUpper.Replace("零角", "零");
            strUpper = strUpper.Replace("零亿零万零圆", "亿圆");
            strUpper = strUpper.Replace("亿零万零圆", "亿圆");
            strUpper = strUpper.Replace("零亿零万", "亿");
            strUpper = strUpper.Replace("零万零圆", "万圆");
            strUpper = strUpper.Replace("零亿", "亿");
            strUpper = strUpper.Replace("零万", "万");
            strUpper = strUpper.Replace("零圆", "圆");
            strUpper = strUpper.Replace("零零", "零");

            // 对壹圆以下的金额的处理
            if (strUpper.Substring(0, 1) == "圆")
            {
                strUpper = strUpper.Substring(1, strUpper.Length - 1);
            }
            if (strUpper.Substring(0, 1) == "零")
            {
                strUpper = strUpper.Substring(1, strUpper.Length - 1);
            }
            if (strUpper.Substring(0, 1) == "角")
            {
                strUpper = strUpper.Substring(1, strUpper.Length - 1);
            }
            if (strUpper.Substring(0, 1) == "分")
            {
                strUpper = strUpper.Substring(1, strUpper.Length - 1);
            }
            if (strUpper.Substring(0, 1) == "整")
            {
                strUpper = "零圆整";
            }
            functionReturnValue = strUpper;

            if (IsNegative == true)
            {
                return "负" + functionReturnValue;
            }
            else
            {
                return functionReturnValue;
            }
        }

        /// <summary>
        /// 人民币大写转换
        /// </summary>
        /// <param name="number">数字</param>
        /// <returns>返回人民币大写,如：壹元整</returns>
        public static string ConvertToChinese(decimal number)
        {
            var s = number.ToString("#L#E#D#C#K#E#D#C#J#E#D#C#I#E#D#C#H#E#D#C#G#E#D#C#F#E#D#C#.0B0A");
            var d = Regex.Replace(s, @"((?<=-|^)[^1-9]*)|((?'z'0)[0A-E]*((?=[1-9])|(?'-z'(?=[F-L\.]|$))))|((?'b'[F-L])(?'z'0)[0A-L]*((?=[1-9])|(?'-z'(?=[\.]|$))))", "${b}${z}");
            var r = Regex.Replace(d, ".", m => "负元空零壹贰叁肆伍陆柒捌玖空空空空空空空分角拾佰仟万亿兆京垓秭穰"[m.Value[0] - '-'].ToString());
            return r;
        }
        #endregion

        /// <summary>
        /// Int类型转换
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static int ToInt(string str)
        {
            try
            {
                return Convert.ToInt32(str);
            }
            catch
            {
                return 0;
            }
        }



    }
}
